package com.taxshare.pvalidate;

import com.taxshare.response.beans.Response;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.List;

/**
 * @ClassName: ParamValidAspect
 * @Description:
 * @author: luozhongyi
 * @date: 2021/1/19 17:12
 */

@Aspect
@Component
@SuppressWarnings("all")
public class ParamValidAspect {

	@Pointcut("@annotation(com.taxshare.pvalidate.ParamValid)")
	public void controllerAspect() {
	}

	@Around("controllerAspect()")
	public Object doControllerAround(ProceedingJoinPoint point) throws Throwable {
		// 获取BindingResult参数校验对象
		BindingResult bindingResult = null;
		Object[] params = point.getArgs();
		for (int i = 0; i < params.length; i++) {
			if (params[i] instanceof BindingResult) {
				bindingResult = (BindingResult) params[i];
				break;
			}
		}
		// 参数信息校验
		if (bindingResult != null && bindingResult.hasErrors()) {
			List<ObjectError> errorList = bindingResult.getAllErrors();
			for (ObjectError error : errorList) {
				return Response.error("500",error.getDefaultMessage());
			}
		}
		return point.proceed();
	}

}
